package com.pyip.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyip.reggie.Entity.Category;
import com.pyip.reggie.Entity.Dish;
import com.pyip.reggie.Entity.Setmeal;
import com.pyip.reggie.common.CustomException;
import com.pyip.reggie.common.R;
import com.pyip.reggie.mapper.CategoryMapper;
import com.pyip.reggie.service.CategoryService;
import com.pyip.reggie.service.DishService;
import com.pyip.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
   @Autowired
   private DishService dishService;
   @Autowired
   private SetmealService setmealService;

    @Override
    public R<Page<Category>> getPage(int page, int pageSize) {
        Page<Category> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> clqw = new LambdaQueryWrapper<>();
        clqw.orderByAsc(Category::getSort);
        baseMapper.selectPage(pageInfo,clqw);
        return R.success(pageInfo);
    }

    @Override
    public R<String> deleteById(Long id) {
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        dlqw.eq(Dish::getCategoryId,id);
        if (dishService.count(dlqw) > 0) {
            // 抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品，不能删除");//已经关联菜品，抛出一个业务异常
        }

        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        slqw.eq(Setmeal::getCategoryId,id);
        if (setmealService.count(slqw) > 0) {
            // 抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐，不能删除");//已经关联套餐，抛出一个业务异常
        }

        return baseMapper.deleteById(id) == 1 ? R.success("删除成功") : R.error("删除失败");
    }


}
